Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports System.Text

Imports ExpertPdf.HtmlToPdf


Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        lblInvoiceReportMessage.Visible = False

        If (Not IsPostBack) Then
            ShowItemsCount()
            LoadInvoiceItems()
        End If
    End Sub

    Private Sub ShowItemsCount()
        lblItemsCount.Text = InvoiceData.GetInvoiceData().IDInvoiceItems.Count.ToString()
    End Sub

    Protected Sub btnAddItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddItem.Click
        If (Not Page.IsValid) Then
            Return
        End If
        If (InvoiceData.GetInvoiceData().IDInvoiceItems.Count >= 100) Then
            lblInvoiceReportMessage.Text = "The maximum number of items reached."
            lblInvoiceReportMessage.Visible = True
            Return
        End If

        Dim newInvoiceItem As InvoiceItem = New InvoiceItem(textBoxProductCode.Text(), textBoxProductDescription.Text, textBoxProductName.Text, Double.Parse(textBoxProductPrice.Text.Trim()), Integer.Parse(textBoxProductQuantity.Text.Trim()))

        InvoiceData.GetInvoiceData().AddItem(newInvoiceItem)

        ShowItemsCount()
        LoadInvoiceItems()
    End Sub

    Protected Sub btnReserItems_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReserItems.Click
        InvoiceData.GetInvoiceData().Reset()
        ShowItemsCount()
        LoadInvoiceItems()
    End Sub

    Protected Sub btnGenerateInvoice_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGenerateInvoice.Click
        If (Not Page.IsValid) Then
            Return
        End If

        ' save customer info on the session 
        ' to make it available in the report page
        SaveCustomerInfo()

        ' get the html string for the report
        Dim htmlStringWriter As StringWriter = New StringWriter()
        Server.Execute("InvoiceReport.aspx", htmlStringWriter)
        Dim htmlCodeToConvert As String = htmlStringWriter.GetStringBuilder().ToString()
        htmlStringWriter.Close()

        ' initialize the PdfConvert object
        Dim pdfConverter As PdfConverter = New PdfConverter()
        pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4
        pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal
        pdfConverter.PdfDocumentOptions.ShowHeader = False
        pdfConverter.PdfDocumentOptions.ShowFooter = False
        ' set the demo license key
        'pdfConverter.LicenseKey = "put your license key here"

        ' get the base url for string conversion which is the url from where the html code was retrieved
        ' the base url is a hint for the converter to find the external CSS and images referenced by relative URLs
        Dim thisPageURL As String = HttpContext.Current.Request.Url.AbsoluteUri
        'Dim baseUrl As String = thisPageURL.Substring(0, thisPageURL.LastIndexOf("/"c)) + "/"
        Dim baseUrl As String = thisPageURL

        ' get the pdf bytes from html string
        Dim downloadBytes As Byte() = pdfConverter.GetPdfBytesFromHtmlString(htmlCodeToConvert, baseUrl)

        Dim response As System.Web.HttpResponse = System.Web.HttpContext.Current.Response
        response.Clear()
        response.AddHeader("Content-Type", "binary/octet-stream")
        response.AddHeader("Content-Disposition", "attachment; filename=Report.pdf; size=" + downloadBytes.Length.ToString())
        response.Flush()
        response.BinaryWrite(downloadBytes)
        response.Flush()
        response.End()
    End Sub

    Protected Sub lnkBtnPreviewReport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkBtnPreviewReport.Click
        If (Not Page.IsValid) Then
            Return
        End If
        InvoiceData.GetInvoiceData().IDCustomerInfo = New CustomerInfo(textBoxCustomerName.Text, textBoxCustomerAddress.Text, textBoxAddress2.Text, textBoxCustomerPhone.Text, textBoxCustomerEmail.Text)

        Response.Redirect("InvoiceReport.aspx")
    End Sub

    Private Sub LoadInvoiceItems()
        itemsGrid.Visible = False
        If (InvoiceData.GetInvoiceData().IDInvoiceItems.Count > 0) Then
            itemsGrid.DataSource = InvoiceData.GetInvoiceData().IDInvoiceItems
            itemsGrid.DataBind()
            itemsGrid.Visible = True
        End If
    End Sub

    Private Sub SaveCustomerInfo()
        InvoiceData.GetInvoiceData().IDCustomerInfo = New CustomerInfo(textBoxCustomerName.Text(), textBoxCustomerAddress.Text(), textBoxAddress2.Text(), textBoxCustomerPhone.Text(), textBoxCustomerEmail.Text())
    End Sub

    Protected Sub cvQuantityValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvQuantityValidator.ServerValidate
        args.IsValid = True
        Try
            Dim quantity As Integer = Integer.Parse(textBoxProductQuantity.Text.Trim())
            If (quantity < 0) Then
                Throw New Exception()
            End If
        Catch
            args.IsValid = False
            Return
        End Try
    End Sub

    Protected Sub cvPriceValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvPriceValidator.ServerValidate
        args.IsValid = True
        Try
            Dim price As Double = Double.Parse(textBoxProductPrice.Text.Trim())
            If (price < 0) Then
                Throw New Exception()
            End If
        Catch
            args.IsValid = False
            Return
        End Try
    End Sub
End Class
